package com.tms.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.tms.domain.Scrap;
import com.tms.mapper.develop.ScrapMapper;
import com.tms.service.ScrapService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 报废记录业务实现
 *
 * @author ozj
 */
@Service
public class ScrapServiceImpl implements ScrapService {

    @Autowired
    private ScrapMapper scrapMapper;

    @Override
    @Cacheable(cacheNames = "scraps", key = "#id", unless = "#result == null")
    public Scrap findScrapById(Integer id) {
        return scrapMapper.selectByPrimaryKey(id);
    }


    @Override
    @CachePut(cacheNames = "scraps", key = "#result.id", unless = "#result == null || #result.id == 0")
    public Scrap createScrap(Scrap scrap) {
        scrapMapper.insertSelective(scrap);
        return scrap;
    }

    @Override
    @Caching(
            evict = {
                    @CacheEvict(cacheNames = "scrapList", allEntries = true, beforeInvocation = true),
                    @CacheEvict(cacheNames = "scraps", key = "#id")
            }
    )
    public void deleteScrapById(Integer id) {
        scrapMapper.deleteByPrimaryKey(id);
    }

    @Override
    @Caching(
            evict = {
                    @CacheEvict(cacheNames = "scrapList", allEntries = true, beforeInvocation = true)
            },
            put = {
                    @CachePut(cacheNames = "scraps", key = "#scrap.id", unless = "#result == null")
            }
    )
    public Scrap updateScrapById(Scrap scrap) {
        int result = scrapMapper.updateByPrimaryKeySelective(scrap);
        if (result == 0) {
            throw new RuntimeException("更新失败，更新结果数为0");
        }
        return scrap;
    }

    @Override
    @Cacheable(cacheNames = "scrapList", key = "#status + 'scrap' + #page + #pageSize + #workcellId", unless = "#result == null")
    public PageInfo<Scrap> findAllScraps(int page, int pageSize, int status, int workcellId) {
        PageHelper.startPage(page, pageSize);
        List<Scrap> list = scrapMapper.selectAlls(status, workcellId);
        return new PageInfo<>(list);
    }
}